// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.ListUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.InventoryList;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryExchangeVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.InventoryListMapper;
import com.fowo.api.mapper.InventoryListSubtableMapper;
import com.fowo.api.model.inventory.list.InventoryListBeginInventoryAction;
import com.fowo.api.model.inventory.list.InventoryListCancellationAction;
import com.fowo.api.model.inventory.list.InventoryListDeleteInventoryAction;
import com.fowo.api.model.inventory.list.InventoryListGetInventoryParam;
import com.fowo.api.model.inventory.list.InventoryListGetInventoryResult;
import com.fowo.api.model.inventory.list.InventoryListItemVo;
import com.fowo.api.model.inventory.list.InventoryListItemVo;
import com.fowo.api.model.inventory.list.InventoryListSearchParamPo;
import com.fowo.api.model.inventory.list.InventoryListSearchParamPo;
import com.fowo.api.model.inventory.list.InventoryListSubmitAction;
import com.fowo.api.model.inventory.list.InventoryListVo;
import com.fowo.api.model.inventory.list.InventoryListVoidInventoryAction;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableItemVo;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableItemVoPages;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableSearchParamPo;
import com.fowo.api.service.InventoryListService;
import com.fowo.api.service.InventoryListSubtableService;
import com.fowo.api.service.impl.InventoryListServiceImpl;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 盘点单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：陈新新，任凯
 */
@Slf4j
@DataObjectType(InventoryList.class)
@DS("ds24")
public class InventoryListBaseServiceImpl
  extends ServiceImpl<InventoryListMapper, InventoryList>
  implements InventoryListService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("warehouseStockName", "w.`name`");
      put("countPeopleName", "su.`name`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected InventoryListService self;

  @Resource
  protected InventoryListSubtableService inventoryListSubtableService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected InventoryListCancellationAction inventoryListCancellationAction;

  @Autowired(required = false)
  protected InventoryListSubmitAction inventoryListSubmitAction;

  @Autowired(required = false)
  protected InventoryListBeginInventoryAction inventoryListBeginInventoryAction;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected InventoryListDeleteInventoryAction inventoryListDeleteInventoryAction;

  @Autowired(required = false)
  protected InventoryListVoidInventoryAction inventoryListVoidInventoryAction;

  @Resource
  protected Validator validator;

  /**
   * 创建盘点单
   * @param model 盘点单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(InventoryListVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryList entity = new InventoryList();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("1");
    }

    if (model.getBlindPlate() == null) {
      entity.setBlindPlate("0");
    }

    if (model.getZeroParticipation() == null) {
      entity.setZeroParticipation(false);
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getInventoryNumber())) {
      entity.setInventoryNumber(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "InventoryList.inventoryNumber")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("盘点单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 盘点单
   */
  protected void updateAllChilds(InventoryListVo model) throws Exception {
    if (model.getGenerateInventoryDetails() != null) {
      inventoryListSubtableService.saveAllByParentInventoryList(
        model.getId(),
        model.getGenerateInventoryDetails()
      );
    }
  }

  /**
   * 更新盘点单
   * @param model 盘点单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(InventoryListVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryList entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("盘点单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "createTime",
      "inventory",
      "firmInventory",
      "stockCount"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新盘点单（带空值）
   * @param model 盘点单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(InventoryListVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryList entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("盘点单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(InventoryList::getLastUpdateTime, model.getLastUpdateTime())
      .set(InventoryList::getLastUpdateUser, model.getLastUpdateUser())
      .set(InventoryList::getWarehouseStock, model.getWarehouseStock())
      .set(InventoryList::getInventoryType, model.getInventoryType())
      .set(InventoryList::getRemark, model.getRemark())
      .set(InventoryList::getCountPeople, model.getCountPeople())
      .set(InventoryList::getBlindPlate, model.getBlindPlate())
      .set(InventoryList::getZeroParticipation, model.getZeroParticipation())
      .set(
        model.getFile() != null,
        InventoryList::getFile,
        JSON.toJSONString(model.getFile())
      )
      .setSql(model.getFile() == null, "file = null")
      .eq(InventoryList::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(InventoryListSearchParamPo search) {
    return false;
  }

  protected boolean checkDeleteById(Long id) {
    return (
      baseMapper.selectCount(
        Wrappers.<InventoryList>query().eq("id", id).eq("status", "1")
      ) ==
      1
    );
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 盘点明细(generateInventoryDetails) 对应的对象
    InventoryListSubtableSearchParamPo generateInventoryDetailsSearchParam =
      new InventoryListSubtableSearchParamPo();
    generateInventoryDetailsSearchParam.setDisableDataPremissions(true);
    generateInventoryDetailsSearchParam.setParentInventoryListInList(ids);
    InventoryListSubtableMapper localInventoryListSubtableMapper = ContextHolder
      .getApplicationContext()
      .getBean(InventoryListSubtableMapper.class);
    generateInventoryDetailsSearchParam.applySqlSegments();
    List<Long> generateInventoryDetailsIdList =
      localInventoryListSubtableMapper.searchIds(
        generateInventoryDetailsSearchParam
      );
    if (!generateInventoryDetailsIdList.isEmpty()) {
      InventoryListSubtableService localInventoryListSubtableService =
        ContextHolder
          .getApplicationContext()
          .getBean(InventoryListSubtableService.class);
      localInventoryListSubtableService.batchDelete(
        generateInventoryDetailsIdList
      );
    }
  }

  /**
   * 删除盘点单
   * @param id 盘点单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    if (!checkDeleteById(id)) {
      throw new RException("不满足操作条件!");
    }
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除盘点单
   * @param ids 盘点单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过盘点仓库查询盘点单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByWarehouseStock(Long warehouseStock) {
    return this.baseMapper.getIdByWarehouseStock(warehouseStock);
  }

  /**
   * 通过盘点仓库查询盘点单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByWarehouseStock(List<Long> list) {
    return this.baseMapper.getIdsByWarehouseStock(list);
  }

  /**
   * 通过盘点单主键查询盘点仓库
   */
  @Override
  public Long getWarehouseStockById(Long id) {
    return this.baseMapper.getWarehouseStockById(id);
  }

  /**
   * 通过盘点单主键查询盘点仓库列表
   */
  @Override
  public List<Long> getWarehouseStockByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getWarehouseStockByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (Long) stringObjectMap.get("warehouseStock"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 盘点单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public InventoryListVo getVoById(Long id) throws Exception {
    InventoryListVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    InventoryListSubtableSearchParamPo generateInventoryDetailsSearchParamPo =
      new InventoryListSubtableSearchParamPo();
    generateInventoryDetailsSearchParamPo.setParentInventoryList(id);
    generateInventoryDetailsSearchParamPo
      .getExtendData()
      .put("queryMode", "sub");
    generateInventoryDetailsSearchParamPo
      .getExtendData()
      .put("queryParent", "InventoryList");
    generateInventoryDetailsSearchParamPo.applySqlSegments();
    vo.setGenerateInventoryDetails(
      inventoryListSubtableService.search(generateInventoryDetailsSearchParamPo)
    );

    return vo;
  }

  /**
   * 主列表上要附加“盘点明细”子表的部分字段
   * @param items 项目列表
   * @param sort 子表排序
   */
  protected void fillPartOfGenerateInventoryDetails(
    List<InventoryListItemVo> items,
    String sort
  ) {
    InventoryListSubtableSearchParamPo generateInventoryDetailsSearchParamPo =
      new InventoryListSubtableSearchParamPo();
    generateInventoryDetailsSearchParamPo.setSort(sort);
    generateInventoryDetailsSearchParamPo.setSelectFields(
      List.of("parentInventoryList", "intensityTime")
    );
    generateInventoryDetailsSearchParamPo.setParentInventoryListInList(
      items
        .stream()
        .map(InventoryListItemVo::getId)
        .collect(Collectors.toList())
    );
    inventoryListSubtableService
      .search(generateInventoryDetailsSearchParamPo)
      .forEach(generateInventoryDetails -> {
        InventoryListItemVo item = ListUtils.find(
          items,
          i ->
            Objects.equals(
              i.getId(),
              generateInventoryDetails.getParentInventoryList()
            )
        );
        if (item == null) return;
        if (item.getGenerateInventoryDetailsIntensityTime() == null) {
          item.setGenerateInventoryDetailsIntensityTime(new ArrayList<>());
        }
        item
          .getGenerateInventoryDetailsIntensityTime()
          .add(generateInventoryDetails.getIntensityTime());
      });
  }

  /**
   * 分页查询盘点单
   * @param search 查询条件
   * @return 盘点单分页查询结果
   */
  @Override
  public Page<InventoryListItemVo> pageSearch(
    InventoryListSearchParamPo search
  ) {
    Page<InventoryListItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(InventoryListItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<InventoryListItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<InventoryListItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    InventoryListSubtableSearchParamPo generateInventoryDetailsSearchParamPo =
      new InventoryListSubtableSearchParamPo();
    generateInventoryDetailsSearchParamPo.setSort(sort);
    generateInventoryDetailsSearchParamPo.setPageSize(200);
    generateInventoryDetailsSearchParamPo.setParentInventoryListInList(
      pageResult
        .getRecords()
        .stream()
        .map(InventoryListItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<InventoryListSubtableItemVoPages>> generateInventoryDetailsMaps =
      inventoryListSubtableService.pagesByParentInventoryList(
        generateInventoryDetailsSearchParamPo
      );

    for (InventoryListItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "generateInventoryDetails",
        generateInventoryDetailsMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 盘点单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(InventoryListSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("generateInventoryDetails")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    InventoryListSearchParamPo search
  ) {
    InventoryListSearchParamPo parentSearchParam =
      new InventoryListSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<InventoryListItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      InventoryListItemVo itemVo = parentList.get(0);

      InventoryListSubtableSearchParamPo generateInventoryDetailsSearchParamPo =
        new InventoryListSubtableSearchParamPo();
      generateInventoryDetailsSearchParamPo.setPageSize(search.getPageSize());
      generateInventoryDetailsSearchParamPo.setCurrent(search.getCurrent());
      generateInventoryDetailsSearchParamPo.setParentInventoryList(
        itemVo.getId()
      );
      return inventoryListSubtableService.pageSearch(
        generateInventoryDetailsSearchParamPo
      );
    } else {
      return null;
    }
  }

  /**
   * 盘点单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'InventoryListOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<InventoryListItemVo>> searchOptions(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询盘点单
   * @param search 查询条件
   * @return 盘点单列表查询结果
   */
  @Override
  public List<InventoryListItemVo> search(InventoryListSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询盘点单最后更新时间
   * @param search 查询条件
   * @return 盘点单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(InventoryListSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Override
  public void cancellation(Long id) throws Exception {
    if (inventoryListCancellationAction == null) {
      throw new Exception("此操作当前不可用");
    }
    inventoryListCancellationAction.run(id);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Override
  public void submit(Long id) throws Exception {
    if (inventoryListSubmitAction == null) {
      throw new Exception("此操作当前不可用");
    }
    inventoryListSubmitAction.run(id);
  }

  /**
   * 开始盘点
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了开始盘点操作"
  )
  @Override
  public void beginInventory(Long id) throws Exception {
    if (inventoryListBeginInventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    inventoryListBeginInventoryAction.run(id);
  }

  /**
   * 锁库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockInventory(Long id) throws Exception {
    InventoryListVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    InventoryList updateStatusEntity = new InventoryList();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存 的参数
   */
  protected InventoryExchangeFormVo prepareLockInventory(InventoryListVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getInventoryNumber());
    formVo.setDocumentType("盘点锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWarehouseStock());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWarehouseStock());
    formVo.setModel(PatternEnum.FIFO);
    for (InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(inventoryListSubtable.getTradeName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(inventoryListSubtable.getInventory()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(inventoryListSubtable.getInventory())
      );
      exchangeItem.setShopId(
        String.valueOf(inventoryListSubtable.getShop()).equals("null")
          ? null
          : String.valueOf(inventoryListSubtable.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            inventoryListSubtable.getFnsku() == null
              ? null
              : inventoryListSubtable.getFnsku().trim()
          )
          ? null
          : String.valueOf(inventoryListSubtable.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        inventoryListSubtable.getShippingSpace(),
        Integer.parseInt(
          String.valueOf(inventoryListSubtable.getInventory()).equals("null")
            ? "0"
            : String.valueOf(inventoryListSubtable.getInventory())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        inventoryListSubtable.getShippingSpace(),
        Integer.parseInt(
          String.valueOf(inventoryListSubtable.getInventory()).equals("null")
            ? "0"
            : String.valueOf(inventoryListSubtable.getInventory())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(inventoryListSubtable.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 释放库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void unLockInventory(Long id) throws Exception {
    InventoryListVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareUnLockInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    InventoryList updateStatusEntity = new InventoryList();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("2");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 释放库存 的参数
   */
  protected InventoryExchangeFormVo prepareUnLockInventory(InventoryListVo vo)
    throws Exception {
    if (!"2".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getInventoryNumber());
    formVo.setDocumentType("盘点释放库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWarehouseStock());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWarehouseStock());
    formVo.setModel(PatternEnum.FIFO);
    for (InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(inventoryListSubtable.getTradeName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(inventoryListSubtable.getInventory()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(inventoryListSubtable.getInventory())
      );
      exchangeItem.setShopId(
        String.valueOf(inventoryListSubtable.getShop()).equals("null")
          ? null
          : String.valueOf(inventoryListSubtable.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            inventoryListSubtable.getFnsku() == null
              ? null
              : inventoryListSubtable.getFnsku().trim()
          )
          ? null
          : String.valueOf(inventoryListSubtable.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        inventoryListSubtable.getShippingSpace(),
        Integer.parseInt(
          String.valueOf(inventoryListSubtable.getInventory()).equals("null")
            ? "0"
            : String.valueOf(inventoryListSubtable.getInventory())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        inventoryListSubtable.getShippingSpace(),
        Integer.parseInt(
          String.valueOf(inventoryListSubtable.getInventory()).equals("null")
            ? "0"
            : String.valueOf(inventoryListSubtable.getInventory())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(inventoryListSubtable.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 锁库存_仓库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存_仓库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockWarehouse(Long id) throws Exception {
    InventoryListVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockWarehouse(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    InventoryList updateStatusEntity = new InventoryList();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存_仓库 的参数
   */
  protected InventoryExchangeFormVo prepareLockWarehouse(InventoryListVo vo)
    throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getInventoryNumber());
    formVo.setDocumentType("盘点锁库存");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWarehouseStock());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWarehouseStock());
    formVo.setModel(PatternEnum.FIFO);
    for (InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(inventoryListSubtable.getTradeName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(inventoryListSubtable.getInventory()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(inventoryListSubtable.getInventory())
      );
      exchangeItem.setShopId(
        String.valueOf(inventoryListSubtable.getShop()).equals("null")
          ? null
          : String.valueOf(inventoryListSubtable.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            inventoryListSubtable.getFnsku() == null
              ? null
              : inventoryListSubtable.getFnsku().trim()
          )
          ? null
          : String.valueOf(inventoryListSubtable.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(inventoryListSubtable.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 释放库存_仓库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放库存_仓库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void unLockWarehouse(Long id) throws Exception {
    InventoryListVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareUnLockWarehouse(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    InventoryList updateStatusEntity = new InventoryList();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("2");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 释放库存_仓库 的参数
   */
  protected InventoryExchangeFormVo prepareUnLockWarehouse(InventoryListVo vo)
    throws Exception {
    if (!"2".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getInventoryNumber());
    formVo.setDocumentType("盘点释放库存");
    if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLastUpdateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWarehouseStock());
    if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWarehouseStock());
    formVo.setModel(PatternEnum.FIFO);
    for (InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(inventoryListSubtable.getTradeName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(inventoryListSubtable.getInventory()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(inventoryListSubtable.getInventory())
      );
      exchangeItem.setShopId(
        String.valueOf(inventoryListSubtable.getShop()).equals("null")
          ? null
          : String.valueOf(inventoryListSubtable.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            inventoryListSubtable.getFnsku() == null
              ? null
              : inventoryListSubtable.getFnsku().trim()
          )
          ? null
          : String.valueOf(inventoryListSubtable.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(inventoryListSubtable.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 删除
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了删除操作"
  )
  @Override
  public void deleteInventory() throws Exception {
    if (inventoryListDeleteInventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    inventoryListDeleteInventoryAction.run();
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Override
  public void voidInventory(List<Long> ids) throws Exception {
    if (inventoryListVoidInventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    inventoryListVoidInventoryAction.run(ids);
  }

  /**
   * 全部
   */
  @Override
  public List<InventoryListItemVo> allInventory(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.allInventory(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<InventoryListItemVo> allInventoryPage(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.allInventoryPage(search.toPage(), search);
  }

  /**
   * 全部最后更新时间
   */
  @Override
  public Date allInventoryLastUpdateTime(InventoryListSearchParamPo search) {
    return this.baseMapper.allInventoryLastUpdateTime(search);
  }

  /**
   * 待盘点
   */
  @Override
  public List<InventoryListItemVo> waitInventory(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.waitInventory(search);
  }

  /**
   * 待盘点分页
   */
  @Override
  public Page<InventoryListItemVo> waitInventoryPage(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.waitInventoryPage(search.toPage(), search);
  }

  /**
   * 待盘点最后更新时间
   */
  @Override
  public Date waitInventoryLastUpdateTime(InventoryListSearchParamPo search) {
    return this.baseMapper.waitInventoryLastUpdateTime(search);
  }

  /**
   * 盘点中
   */
  @Override
  public List<InventoryListItemVo> inventorying(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.inventorying(search);
  }

  /**
   * 盘点中分页
   */
  @Override
  public Page<InventoryListItemVo> inventoryingPage(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.inventoryingPage(search.toPage(), search);
  }

  /**
   * 盘点中最后更新时间
   */
  @Override
  public Date inventoryingLastUpdateTime(InventoryListSearchParamPo search) {
    return this.baseMapper.inventoryingLastUpdateTime(search);
  }

  /**
   * 已盘点
   */
  @Override
  public List<InventoryListItemVo> inventoryed(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.inventoryed(search);
  }

  /**
   * 已盘点分页
   */
  @Override
  public Page<InventoryListItemVo> inventoryedPage(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.inventoryedPage(search.toPage(), search);
  }

  /**
   * 已盘点最后更新时间
   */
  @Override
  public Date inventoryedLastUpdateTime(InventoryListSearchParamPo search) {
    return this.baseMapper.inventoryedLastUpdateTime(search);
  }

  /**
   * 已作废
   */
  @Override
  public List<InventoryListItemVo> inventoryAbrogate(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.inventoryAbrogate(search);
  }

  /**
   * 已作废分页
   */
  @Override
  public Page<InventoryListItemVo> inventoryAbrogatePage(
    InventoryListSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", InventoryListServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.inventoryAbrogatePage(search.toPage(), search);
  }

  /**
   * 已作废最后更新时间
   */
  @Override
  public Date inventoryAbrogateLastUpdateTime(
    InventoryListSearchParamPo search
  ) {
    return this.baseMapper.inventoryAbrogateLastUpdateTime(search);
  }

  /**
   * 生成盘点明细
   */
  @Override
  public InventoryListGetInventoryResult getInventory(
    InventoryListGetInventoryParam param
  ) {
    return this.baseMapper.getInventory(param);
  }
}
